package com.lucifer.treasure.enchant.effect;

import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.fabricmc.fabric.api.event.player.UseItemCallback;
import net.minecraft.enchantment.EnchantmentEffectContext;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.enchantment.EnchantmentLevelBasedValue;
import net.minecraft.enchantment.effect.EnchantmentEntityEffect;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.projectile.thrown.EnderPearlEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.SwordItem;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;

public record EnderPearlEnchantmentEffect(EnchantmentLevelBasedValue teleport) implements EnchantmentEntityEffect {
    public static final MapCodec<EnderPearlEnchantmentEffect> CODEC = RecordCodecBuilder.mapCodec(instance ->
            instance.group(
                    EnchantmentLevelBasedValue.CODEC.fieldOf("teleport").forGetter(EnderPearlEnchantmentEffect::teleport)
            ).apply(instance, EnderPearlEnchantmentEffect::new)
    );

    // 配置常量
    private static final int BASE_COOLDOWN = 120; // 6秒基础冷却
    private static final float VELOCITY = 1.5f; // 与原版末影珍珠相同
    private static final float INACCURACY = 1.0f; // 与原版末影珍珠相同
    private static final int DURABILITY_COST = 1; // 耐久消耗

    public static void initialize() {
        // 注册右键使用物品事件
        UseItemCallback.EVENT.register((player, world, hand) -> {
            return handleEnderPearlUse(player, world, hand);
        });
    }

    /**
     * 处理末影珍珠附魔的使用
     */
    private static TypedActionResult<ItemStack> handleEnderPearlUse(PlayerEntity player, World world, Hand hand) {
        ItemStack stack = player.getStackInHand(hand);

        // 检查是否是剑且有EnderPearl附魔
        if (!(stack.getItem() instanceof SwordItem)) {
            return TypedActionResult.pass(stack);
        }

        int level = getEnderPearlLevel(stack);
        if (level <= 0) {
            return TypedActionResult.pass(stack);
        }

        // 检查冷却
        int adjustedCooldown = BASE_COOLDOWN / level; // 等级越高冷却越短
        if (player.getItemCooldownManager().isCoolingDown(stack.getItem())) {
            return TypedActionResult.pass(stack);
        }

        // 只在服务器端执行
        if (!world.isClient()) {
            // 创建末影珍珠实体
            EnderPearlEntity enderPearl = new EnderPearlEntity(world, player);

            // 设置投掷方向和速度
            Vec3d lookDirection = player.getRotationVec(1.0f);
            enderPearl.setVelocity(player, player.getPitch(), player.getYaw(), 0.0f, VELOCITY, INACCURACY);

            // 添加到世界
            world.spawnEntity(enderPearl);

            // 播放音效
            world.playSound(null, player.getX(), player.getY(), player.getZ(),
                    SoundEvents.ENTITY_ENDER_PEARL_THROW, SoundCategory.PLAYERS,
                    0.5f, 0.4f + (world.getRandom().nextFloat() * 0.4f + 0.8f));

            // 生成粒子效果
            if (world instanceof ServerWorld serverWorld) {
                serverWorld.spawnParticles(ParticleTypes.PORTAL,
                        player.getX(), player.getY() + 1.0, player.getZ(),
                        15, // 粒子数量
                        0.5, 0.5, 0.5, // 扩散范围
                        0.1 // 初始速度
                );

                // 额外的末影粒子效果
                serverWorld.spawnParticles(ParticleTypes.REVERSE_PORTAL,
                        player.getX(), player.getY() + 0.5, player.getZ(),
                        8, // 粒子数量
                        0.3, 0.3, 0.3, // 扩散范围
                        0.05 // 初始速度
                );
            }

            // 设置冷却
            player.getItemCooldownManager().set(stack.getItem(), adjustedCooldown);

            // 消耗耐久度
            EquipmentSlot slot = hand == Hand.MAIN_HAND ? EquipmentSlot.MAINHAND : EquipmentSlot.OFFHAND;
            stack.damage(DURABILITY_COST, player, slot);
        }

        return TypedActionResult.success(stack, world.isClient());
    }

    /**
     * 获取物品栈的EnderPearl附魔等级
     */
    private static int getEnderPearlLevel(ItemStack stack) {
        if (stack.isEmpty()) {
            return 0;
        }

        var enchantments = EnchantmentHelper.getEnchantments(stack);
        return enchantments.getEnchantments().stream()
                .filter(entry -> {
                    if (entry.getKey().isPresent()) {
                        return entry.getKey().get().getValue().toString().equals("lucifer_treasure:ender_pearl");
                    }
                    return false;
                })
                .mapToInt(entry -> enchantments.getLevel(entry))
                .max()
                .orElse(0);
    }

    @Override
    public void apply(ServerWorld world, int level, EnchantmentEffectContext context, Entity target, Vec3d pos) {
        // 主要逻辑在使用物品事件中处理
        // 这里可以添加持续的末影效果
        if (target instanceof PlayerEntity player) {
            // 添加微妙的末影粒子效果表示附魔存在
            if (world.getRandom().nextInt(200) < 1) { // 0.5%概率
                world.spawnParticles(ParticleTypes.PORTAL,
                        target.getX(), target.getY() + 0.1, target.getZ(),
                        1, 0.1, 0.1, 0.1, 0.01);
            }
        }
    }

    @Override
    public MapCodec<? extends EnchantmentEntityEffect> getCodec() {
        return CODEC;
    }
} 